﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.Objects;

namespace VLUSM_DataAccess.Repositories
{
    public abstract class GenericRepository<C, T> :
        IGenericRepository<T>
        where T : class
        where C : ObjectContext, new()
    {
        private C context = new C();
        public C Context
        {
            get { return context; }
            set { context = value; }
        }

        public virtual IEnumerable<T> SelectAll()
        {
            IEnumerable<T> query = context.CreateObjectSet<T>();
            return query;
        }

        public virtual T SelectOne(System.Linq.Expressions.Expression<Func<T, bool>> predicate)
        {
            T entity = context.CreateObjectSet<T>().Where(predicate).FirstOrDefault<T>();
            return entity;
        }

        public IEnumerable<T> SelectWhere(System.Linq.Expressions.Expression<Func<T, bool>> predicate)
        {
            IQueryable<T> query = context.CreateObjectSet<T>().Where(predicate);
            return query;
        }

        public virtual void Add(T entity)
        {
            string entityType = entity.GetType().ToString();
            int start = entityType.LastIndexOf(".") + 1;
            string entityName = entityType.Substring(start, entityType.Length - start);

            context.AddObject(String.Format("{0}.{1}s", context.DefaultContainerName, entityName), entity);
        }

        public virtual void Delete(T entity)
        {
            context.DeleteObject(entity);
        }

        public virtual void Edit(T entity)
        {
            context.ObjectStateManager.ChangeObjectState(entity, System.Data.EntityState.Modified);
        }

        public virtual void Save()
        {
            context.SaveChanges();
        }
    }
}
